<?php
/**
 *
 * @author Amissah Gideon<kuulmek@yahoo.com>
 * @access public
 * @version 1.0
 * @copyright (c) 2011.
 */

class AccountController extends AppController {
    # Controller Name to be used
   var $name = 'Account';

  # Models to be used
   var $uses = array(
       'User',
       'Organisation',
       'Module',
       'Configuration',
       'PropertyItem',
       'PropertyItemDetail',
       'PropertyGroup',
       'Location',
       'PropertyGroupType',
       'PropertyGroupSubType',
       'Bill',
       'BillComponent',
       'BillProperty',
       'BillPayment'	   
   );


   # set the layout to use
   var $layout = 'account_layout';
   
   # set the name of this module
   var $moduleName = 'Account';

   # Check the authenticity of the user
   function  beforeFilter() {
          parent::setUpGlobalConfig();
          # Check the user validity
          if($this->Session->check('userSessionData')){
                 $loggedUser =  $this->Session->read('userSessionData');
                 $userData = $this->User->getUserById($loggedUser['id']);
                 $userModules = $userData['Module'];
                 $allowed = false;
                 foreach($userModules as $module){
                    if($module['name'] === $this->moduleName){
                        $allowed = true;
                    }
                 }
                 if(!$allowed){
                      $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
                 }
          }
          else{
                  $this->redirect('/');
          }
   }
   
   # Controller actions
   /**
    * This function displays all the users in the system
    * @name index
    * @param void
    * @return Array of data.
    * @access public
    */
   function index(){			
		
   }
   
   
    /**
    * This function add all new bill 
    * @name add
    * @param void
    * @return Array of data.
    * @access public
    */
   function add(){			
    	$this->autoRender = false;
        $this->autoLayout = false;
        $model = $_POST['model'];
             # Check the model
             switch($model){
                case 'ModifyBill' : 
                    $upt_id = ($_POST['row_id'] != 'null') ? $_POST['row_id'] : false;
                    //$property_detail_id =  $_POST['property_detail_id'];
                	$loggedUser =  $this->Session->read('userSessionData');
                	$loggedUser_id = $loggedUser['id'];
                	$save_date = date('Y-m-d');
                    
                    /** Check if bill exist **/
                    $billData = $this->Bill->find('first',array(
                        'conditions'=>array(
                            'property_group_id'         =>$this->request->data['Bill']['property_group_id'],
                            'location_id'               =>$this->request->data['Bill']['location_id'],
                            'property_group_type_id'    =>$this->request->data['Bill']['property_group_type_id'],
                            'property_group_sub_type_id'=>$this->request->data['Bill']['property_group_sub_type_id'],
                            'year'                      =>$this->request->data['Bill']['year'],
                            'deleted'                    =>0
                        ),
                        'recursive'=> -1
                    ));
                    
                    
                    if($upt_id){ /** Edit*/
                        if(!empty($billData)){
                            $bill_id = $billData['Bill']['id'];
                            if(!($bill_id == $upt_id)){
                                return json_encode(array('code' => 1, 'mesg' => 'Bill Already Exist!'));
                            }
                        }
                		$this->Bill->id = $upt_id;
                	}
                	else{ /** New*/
                         if(!empty($billData)){
                            return json_encode(array('code' => 1, 'mesg' => 'Bill Already Exist!'));
                         }
                		$this->Bill->create();
                        $this->request->data['Bill']['date'] = $save_date;
                	}
                    
                    # save the data
            		if($this->Bill->save($this->request->data)){
               			  return json_encode(array('code' => 0, 'mesg' => 'Data Saved'));
            		}
            		else{
            			  return json_encode(array('code' => 1, 'mesg' => $this->Bill->invalidFields()));
            		}    
                                                
                 break; 
                 
                 case 'BillComponent' : 
                    $bill_id = ($_POST['row_id'] != 'null') ? $_POST['row_id'] : false;
                    $upt_id = ($_POST['upt_id'] != 'null') ? $_POST['upt_id'] : false;
                    
                	$loggedUser =  $this->Session->read('userSessionData');
                	$loggedUser_id = $loggedUser['id'];
                	$save_date = date('Y-m-d');
                    $this->request->data['BillComponent']['bill_id'] = $bill_id;
                    
                    if($upt_id){ /** Edit*/
                		$this->BillComponent->id = $upt_id;
                	}
                	else{ /** New*/
                		$this->BillComponent->create();
                        		
                	}
                    
                    # save the data
            		if($this->BillComponent->save($this->request->data)){
            		      $tl = $this->__sumBillTotals($bill_id);
               			  return json_encode(array('code' => 0, 'billTotal'=>$tl,'data_id'=>$this->BillComponent->id,'mesg' => 'Data Saved'));
            		}
            		else{
            			  return json_encode(array('code' => 1, 'mesg' => $this->BillComponent->invalidFields()));
            		}    
                                                
                 break;
                 
                 case 'BillPayment' : 
                    
                	$loggedUser =  $this->Session->read('userSessionData');
                	$loggedUser_id = $loggedUser['id'];
                	$save_date = date('Y-m-d');
                    
                    $this->request->data['BillPayment']['date'] = $save_date;
                    $this->request->data['BillPayment']['receipt_no'] = $this->__generateReceiptNo();
                	$this->BillPayment->create();
                        		
                    # save the data
            		if($this->BillPayment->save($this->request->data)){
               			  return json_encode(array('code' => 0, 'data_id'=>$this->BillPayment->id,'mesg' => 'Data Saved'));
            		}
            		else{
            			  return json_encode(array('code' => 1, 'mesg' => $this->BillPayment->invalidFields()));
            		}    
                                                
                 break;
    
             }
   }
   
   
   function modifyBill(){
        $prpGroup = Hash::combine($this->PropertyGroup->find('all',array('conditions' => array('deleted'=>0),'fields'=>array('id','group_name'),'recursive'=>-1)),'{n}.PropertyGroup.id', '{n}.PropertyGroup');
        //$jsonArr = array(array('name'=>'All','value'=>0));
        $jsonArr = array();
        foreach($prpGroup as $key => $value){
            $jsonArr[] = array('name'=>$value['group_name'],'value'=>$value['id']);
        }

        $prpFieldGroup = $this->PropertyGroup->find('all',array(
                'fields'=>array('id','group_name','fields'),
                'conditions' => array('deleted'=>0),
                'contain'=>array(
                    'PropertyGroupType'=>array(
                        'fields'=>array('id','type_name'),
                        'conditions' => array('deleted'=>0),
                        'PropertyGroupSubType'=>array(
                            'fields'=>array('id','sub_type_name'),
                            'conditions' => array('deleted'=>0)
                        )
                    ),
                ),
                'recursive'=>2
            )
        );
        //debug($prpFieldGroup);
        $prpGroupData = array();
        
    /** $prpGroupData['0']['id'] = 0;
        $prpGroupData['0']['group_name'] = 'All';
        $prpGroupData['0']['fields'] = array('property_group_id','location_id');
        $prpGroupData['0']['group_type']['0']['id'] = 0;
        $prpGroupData['0']['group_type']['0']['type_name'] = 'All';
        $prpGroupData['0']['group_type']['0']['group_sub_type']['0']['id'] = 0;
        $prpGroupData['0']['group_type']['0']['group_sub_type']['0']['sub_type_name'] = 'All';*/
        
        foreach($prpFieldGroup as $value){
            $prpGroupData[$value['PropertyGroup']['id']]['id'] = $value['PropertyGroup']['id'];
            $prpGroupData[$value['PropertyGroup']['id']]['group_name'] = $value['PropertyGroup']['group_name'];
            
            if($value['PropertyGroup']['fields']){
                $fields_arr = explode(',',$value['PropertyGroup']['fields']);
                foreach($fields_arr as $value_0){
                    $prpGroupData[$value['PropertyGroup']['id']]['fields'][] = $value_0;
                }
            }
            else{
                $prpGroupData[$value['PropertyGroup']['id']]['fields'] = array();
            }
            
            $prpGroupData[$value['PropertyGroup']['id']]['group_type']['0']['id'] = 0;
            $prpGroupData[$value['PropertyGroup']['id']]['group_type']['0']['type_name'] = 'All';
            $prpGroupData[$value['PropertyGroup']['id']]['group_type']['0']['group_sub_type']['0']['id'] = 0;
            $prpGroupData[$value['PropertyGroup']['id']]['group_type']['0']['group_sub_type']['0']['sub_type_name'] = 'All';
            foreach($value['PropertyGroupType'] as $value_1){
                $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['id'] = $value_1['id'];
                $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['type_name'] = $value_1['type_name'];
                
                $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['group_sub_type']['0']['id'] = 0;
                $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['group_sub_type']['0']['sub_type_name'] = 'All';
                foreach($value_1['PropertyGroupSubType'] as $value_2){
                    $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['group_sub_type'][$value_2['id']]['id'] = $value_2['id'];
                    $prpGroupData[$value['PropertyGroup']['id']]['group_type'][$value_1['id']]['group_sub_type'][$value_2['id']]['sub_type_name'] = $value_2['sub_type_name'];
                }
            }
            
        }
        
        $loc_data = Hash::combine($this->Location->find('all',array(
                'fields'=>array('id','location_name','location_code'),
                'conditions' => array('deleted'=>0),
                'recursive'=>-1
            )
        ),'{n}.Location.id', '{n}.Location');
        
        $this->set(compact('jsonArr','prpGroupData','loc_data')); 
   }
   
   
  /** function __applyOrPrintBill ($idsP){        
        $data = $this->Bill->find('first',array(
                'fields'=>array('id','property_group_id','location_id','property_group_type_id','property_group_sub_type_id'),
                'conditions' => array('id'=>$idsP,'deleted'=>0),
                'recursive'=>-1
            )
        );
        $group_id = $data['Bill']['property_group_id'];
        $location_id = $data['Bill']['location_id'];
        $group_type_id = $data['Bill']['property_group_type_id'];
        $group_sub_type_id = $data['Bill']['property_group_sub_type_id'];
        
        
        $conditions = array(
            'PropertyItem.property_group_id'=>$group_id, 
            'PropertyItem.deleted'=>0, 
        );
        
        if(intval($location_id) != 0){
            $conditions['PropertyItem.location_id'] = $location_id;
        }
        if(intval($group_type_id) != 0){
            $conditions['PropertyItem.property_group_type_id'] = $group_type_id;
        }
        if(intval($group_sub_type_id) != 0){
            $conditions['PropertyItem.property_group_sub_type_id'] = $group_sub_type_id;
        }
        
        $prpData = $this->PropertyItem->find('all',array(
                'fields'=>array('id','name','property_reg_no','owners_name'),
                'conditions' => $conditions,
                'contain'=>array(
                    'PropertyGroup'=>array(
                        'fields'=>array('id','group_name'),
                    ),
                    'PropertyItemDetail'=>array('fields'=>array('id','permit_no')),
                    'PropertyGroupType'=>array('fields'=>array('id','type_name')),
                    'PropertyGroupSubType'=>array('fields'=>array('id','property_group_type_id','sub_type_name')), 
                    'BillProperty'=>array(
                       'conditions' => array(
                            'bill_id'=> $idsP
                        ),
                        //'fields'=>array('id','bill_id','property_id')
                    )
                ),
                'recursive'=>1
            )
        );
        
        $return_arr = $prpData;
        
        return $return_arr;
   }   */
   
   
   function loadBillForApplication(){
        $bill_id = $_POST['ids'];
        $data = $this->Bill->find('first',array(
                'fields'=>array('id','property_group_id','location_id','property_group_type_id','property_group_sub_type_id'),
                'conditions' => array('id'=>$bill_id,'deleted'=>0),
                'recursive'=>-1
            )
        );
        $group_id = $data['Bill']['property_group_id'];
        $location_id = $data['Bill']['location_id'];
        $group_type_id = $data['Bill']['property_group_type_id'];
        $group_sub_type_id = $data['Bill']['property_group_sub_type_id'];
        
        $conditions = array(
            'PropertyItem.property_group_id'=>$group_id, 
            'PropertyItem.deleted'=>0, 
        );
        
        if(intval($location_id) != 0){
            $conditions['PropertyItem.location_id'] = $location_id;
        }
        if(intval($group_type_id) != 0){
            $conditions['PropertyItem.property_group_type_id'] = $group_type_id;
        }
        if(intval($group_sub_type_id) != 0){
            $conditions['PropertyItem.property_group_sub_type_id'] = $group_sub_type_id;
        }
        
        $prp_datax = $this->PropertyItem->find('all',array(
                'fields'=>array('id','name','property_reg_no','owners_name'),
                'conditions' => $conditions,
               /* 'contain'=>array(
                  'BillProperty'=>array(
                        'fields'=>array('id','bill_id','property_item_id')
                    )
                ),*/
                'recursive'=>-1
            )
        );
        
        $prp_ids_arr = array();
        $frmt_properties = array();
        foreach($prp_datax as $key => $value){
            $prp_id = $value['PropertyItem']['id'];
            $prp_ids_arr[] = $prp_id;
            $frmt_properties[$prp_id] = $value;
            $frmt_properties[$prp_id]['BillProperty'] = array();
        }
        
        $billPropData = $this->BillProperty->find('all',array(
                'fields'=>array('id','bill_id','property_item_id'),
                'conditions' => array('BillProperty.property_item_id'=>$prp_ids_arr),
                'recursive'=>-1
            )
        );
        
        foreach($billPropData as $key => $value){
          $prop_item_id =  $value['BillProperty']['property_item_id'];
          $frmt_properties[$prop_item_id]['BillProperty'][$key] = $value;
        }
        
        
        //debug($frmt_properties);              
        $prp_data = $frmt_properties;  
               
        $this->set(compact('prp_data'));  
   }
   
   function applyBill(){
        $this->autoRender = false;
        $this->autoLayout = false;
        
        $ids = $_POST['ids'];
        $bill_id = $_POST['bill_id'];
        $type = $_POST['type'];
		
        if($type == 'apply'){
            foreach($ids as $key => $id){
                /** Check if record exist **/
                $billPrp = $this->BillProperty->find('first',array(
                        'conditions' => array('BillProperty.bill_id'=>$bill_id, 'BillProperty.property_item_id'=>$id),
                        'recursive'=>-1
                    )
                );
                if(empty($billPrp)){
                    $data['BillProperty'][$key]=array(
                        'bill_id'     => $bill_id,
                        'property_item_id' => $id,
                    );
                }
            }
            $result = $this->BillProperty->saveAll($data['BillProperty']);
            if($result){
    			echo json_encode(array('code' => 0, 'mesg' => 'Bill Applied Successfully'));
    		}
    		else{
    			echo json_encode(array('code' => 1, 'mesg' => 'Bill Cannot Be Applied'));
    		}
        }
        else{
            $result = $this->BillProperty->deleteAll(
                array('BillProperty.bill_id'=>$bill_id, 'BillProperty.property_item_id'=>$ids),
                false
            );
            if($result){
    			echo json_encode(array('code' => 0, 'mesg' => 'Bill Removed Successfully'));
    		}
    		else{
    			echo json_encode(array('code' => 1, 'mesg' =>'Bill Cannot Be Removed'));
    		}
        }	
   }
   
   
   function loadBillForPrint(){
        
        $billPrp = $this->BillProperty->find('all',array(
                'conditions' => array('BillProperty.bill_id'=>$_POST['ids']),
                'contain'=>array(
                    'PropertyItem'=>array(
                        'fields'=>array('id','name','property_reg_no','owners_name')
                    )
                ),
                'recursive'=>1
            )
        );
        $prpData = $billPrp;         
        $this->set(compact('prpData'));      
   }
   

   function printData (){
        $this->autoLayout = false;
        $bill_id = explode(',',$_POST['bill_id']);
        $ids = explode(',',$_POST['ids']);
        array_pop($ids);
        
        $billData = $this->Bill->find('first',array(
                'conditions' => array('Bill.id'=>$bill_id),
                'contain'=>array(
                   /** 'PropertyGroup' => array(
                        'fields'=>array('id','group_name')
                     ),
                     'Location' => array(
                        'fields'=>array('id','location_name','location_code')
                     ),
                     'PropertyGroupType' => array(
                        'fields'=>array('id','type_name')
                     ),
                     'PropertyGroupSubType' => array(
                        'fields'=>array('id','sub_type_name')
                     ), */
                     'BillComponent' => array(
                        'fields'=>array('id','comp_name','amount')
                     )
                ),
                'recursive'=>1
            )
        );
        
        $total = $this->__sumBillTotals($billData['BillComponent']);
        
        $billPrp = $this->BillProperty->find('all',array(
                'conditions' => array('BillProperty.bill_id'=>$bill_id, 'BillProperty.property_item_id'=>$ids),
                'contain'=>array(
                    'PropertyItem'=>array(
                        'fields'=>array('id','name','property_reg_no','owners_name','other_partners_name','house_no','telephone','business_no','latitude','longitude','elevation')
                    )
                ),
                'recursive'=>2
            )
        ); 
         
        $this->set(compact('billPrp','total','billData'));  
   }
   
   
   function getBillList (){
        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;
        
        //return json_encode(array('success' => false, 'total'=>0, 'page' => 1, 'rows' => array()));
        
        /**  Get posted data */
        $page =      isset($_POST['page']) ? $_POST['page'] : 1 ; /** The current page */
        $sortname =  isset($_POST['sortname']) ? $_POST['sortname'] : 'id' ; /** Sort column */
        $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc' ; /** Sort order */
        $qtype =     isset($_POST['qtype']) ? $_POST['qtype'] : '' ; /** Search column */
        $search_query =     isset($_POST['query']) ? $_POST['query'] : '' ; /** Search string */
        $rp =        isset($_POST['rp']) ? $_POST['rp'] : 10 ;
        
        $limit = $rp;
        $start = ($page-1) * $rp;
        
        $condition_array = array('Bill.deleted' => 0);        
        
        $contain = array(
             'PropertyGroup' => array(
                'fields'=>array('id','group_name')
             ),
             'Location' => array(
                'fields'=>array('id','location_name','location_code')
             ),
             'PropertyGroupType' => array(
                'fields'=>array('id','type_name')
             ),
             'PropertyGroupSubType' => array(
                'fields'=>array('id','sub_type_name')
             ),
             'BillComponent' => array(
                'fields'=>array('id','comp_name','amount')
             ),
        );
        $fields = array('Bill.id','Bill.year');
        $order = "Bill.$sortname $sortorder";
        if($sortname == 'group_name'){
            $order = "PropertyGroup.$sortname $sortorder";
        }
        elseif($sortname == 'type_name'){
            $order = "PropertyGroupType.$sortname $sortorder";
        }
        elseif($sortname == 'sub_type_name'){
            $order = "PropertyGroupSubType.$sortname $sortorder";
        }
        
        $billData = $this->Bill->find('all', array(
            'contain'=>$contain ,
            'fields'=>$fields,
            'conditions' => $condition_array,
            'order' => $order,
            'limit'=>$limit,
            'offset'=>$start,
            'recursive' => 1
        ));
   
        
        $billCount  = $this->Bill->find('count', array(
            'conditions' => $condition_array,
            'recursive' => -1
        ));
        
        $total_records = $billCount;        
                
        if($billData){
            $return_arr = array();
            foreach ($billData as $obj){
               
               $group_name = isset($obj['PropertyGroup']['group_name']) ? $obj['PropertyGroup']['group_name'] : 'All';
               $location_name = isset($obj['Location']['location_name']) ? $obj['Location']['location_name'] : 'All';
               $type_name = isset($obj['PropertyGroupType']['type_name']) ? $obj['PropertyGroupType']['type_name'] : 'All';
               $sub_type_name = isset($obj['PropertyGroupSubType']['sub_type_name']) ? $obj['PropertyGroupSubType']['sub_type_name'] : 'All';
               $tl = $this->__sumBillTotals($obj['BillComponent']);
               $return_arr[] = array(
                    'id' => $obj['Bill']['id'],
                    'cell' => array(
                        $obj['Bill']['id'], 
                        $group_name, 
                        $location_name,
                        $type_name, 
                        $sub_type_name,
                        $obj['Bill']['year'],
                        $tl
                    )
               );                  
            }
           return json_encode(array('success' => true, 'total'=>$total_records, 'page' => $page,'rows' => $return_arr));
        }
        else{
           return json_encode(array('success' => false, 'total'=>$total_records, 'page' => $page, 'rows' => array()));
        }	
         
   }
   
   
   function getBill (){
        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false; 
		
		$ids = isset($_POST['ids']) ? json_decode($_POST['ids']) : 0;
        
        $contain = array(
             'PropertyGroup' => array(
                'fields'=>array('id','group_name')
             ),
             'Location' => array(
                'fields'=>array('id','location_name','location_code')
             ),
             'PropertyGroupType' => array(
                'fields'=>array('id','type_name')
             ),
             'PropertyGroupSubType' => array(
                'fields'=>array('id','sub_type_name')
             ),
             'BillComponent' => array(
                'fields'=>array('id','comp_name','amount')
             ),
        );
        
        $billData = $this->Bill->find('first',array(
            'conditions'=>array('Bill.id'=>$ids, 'Bill.deleted' => 0),
            'contain'=> $contain,
            'recursive' => 1
        ));
        
        $tl = $this->__sumBillTotals($billData['BillComponent']);
        
        $billData['BillTotal'] = $tl;
        
        if($billData){                
           return json_encode(array('code' => 0, 'data'=>$billData));
        }
        else{
           return json_encode(array('code' => 1, 'data'=> array()));
        }    
   }
   
   
    #Delete Users via ajax
    function deleteBill(){
        $loggedUser =  $this->Session->read('userSessionData');
		if($this->request->is('ajax')){
			$this->autoRender = false;
			$this->autoLayout = false;
             
            $ids = $_POST['ids'];
            $items = ClassRegistry::init('Bill');
            $result = $items->updateAll(
				array('Bill.deleted' => 1 ), 
				array('Bill.id' => $ids)
			);
			
			if($result){
				 echo json_encode(array('code' => 0, 'mesg' => 'Data successfully deleted'));
			}
			else{
				echo json_encode(array('code' => 1, 'mesg' => 'Data cannot be deleted'));
			}
         }
	}
    
    
    /** Bills Payment **/
    function billsPayment($id){        
       $contain = array(
             'PropertyGroup' => array(
                'fields'=>array('id','group_name')
             ),
             'Location' => array(
                'fields'=>array('id','location_name','location_code')
             ),
             'PropertyGroupType' => array(
                'fields'=>array('id','type_name')
             ),
             'PropertyGroupSubType' => array(
                'fields'=>array('id','sub_type_name')
             )
        );
        
        $fields = array('PropertyItem.id','PropertyItem.property_reg_no','PropertyItem.loc_region','PropertyItem.name','PropertyItem.owners_name');
        $propData = $this->PropertyItem->find('first', array(
            'contain'=>$contain ,
            'fields'=>$fields,
            'conditions' => array('PropertyItem.id'=>$id),
            'recursive' => 1
        ));
        
        /** Bill Data*/
        $billData = $this->BillProperty->find('all', array(
            'conditions' => array('BillProperty.property_item_id'=>$id),
            'contain'=>array(
                'Bill' => array(
                    'fields'=>array('id','year'),
                    'BillComponent' => array(
                        'fields'=>array('id','comp_name','amount')
                    )
                ),
                'BillPayment'=>array(
                    'fields'=>array('id','amount')
                )
            ) ,
            'recursive' => 2
        ));
        
        foreach($billData as $bkey => $bill){
            $billData[$bkey]['Bill']['total'] = $this-> __sumBillTotals($bill['Bill']['BillComponent']);
            $billData[$bkey]['Total Payment'] = $this-> __sumPaymentTotals($bill['BillPayment']);
        }
        
        $this->set(compact('propData','billData')); 
    }
    
    
    function printReceipt($id){
        $this->autoLayout = false;
        /** Payment Data*/
        $paymentData = $this->BillPayment->find('first', array(
            'fields'=>array('id','property_item_id','amount','date','type','receipt_no','recieved_from'),
            'conditions' => array('BillPayment.id'=>$id),
            'contain'=>array(
                'PropertyItem' => array(
                    'fields'=>array('id','property_reg_no','loc_region','name','owners_name'),
                )
            ),
            'recursive' => 1
        ));
        
        /** Bill Data*/
        $billData = $this->BillProperty->find('all', array(
            'conditions' => array('BillProperty.property_item_id'=>$paymentData['BillPayment']['property_item_id']),
            'contain'=>array(
                'Bill' => array(
                    'fields'=>array('id','year'),
                    'BillComponent' => array(
                        'fields'=>array('id','comp_name','amount')
                    )
                ),
                'BillPayment'=>array(
                    'fields'=>array('id','amount')
                )
            ) ,
            'recursive' => 2
        ));
        
        foreach($billData as $bkey => $bill){
            $billData[$bkey]['Bill']['total'] = $this-> __sumBillTotals($bill['Bill']['BillComponent']);
            $billData[$bkey]['Total Payment'] = $this-> __sumPaymentTotals($bill['BillPayment']);
        }
        
        $ttl_bill = 0.00;
        $ttl_payment = 0.00;
        foreach($billData as $bkey => $bill){
          $ttl_bill = $ttl_bill + $bill['Bill']['total'];
          $ttl_payment = $ttl_payment + $bill['Total Payment'];
         
        }
        $credit = 0.00;
        $debit = 0.00;
        $diff = $ttl_bill - $ttl_payment;
        if($diff < 0){/** Credit **/
            $credit = $diff * -1;
        }
        else{/** Dedit **/
         $debit = $diff;
        }
        
        $this->set(compact('paymentData','credit','debit'));  
    }
    
        
    function deleteBillComponent(){
        $loggedUser =  $this->Session->read('userSessionData');
		if($this->request->is('ajax')){
			$this->autoRender = false;
			$this->autoLayout = false;
             
            $id = $_POST['id'];
            $items = ClassRegistry::init('BillComponent');
            $result = $items->updateAll(
				array('BillComponent.deleted' => 1 ), 
				array('BillComponent.id' => $id)
			);
			
			if($result){
				 echo json_encode(array('code' => 0, 'mesg' => 'Data successfully deleted'));
			}
			else{
				echo json_encode(array('code' => 1, 'mesg' => 'Data cannot be deleted'));
			}
         }
	}
    
    
    function veiwBillPaymentInfo(){
        $bill_property_id = $_POST['id'];
        $property_id = $_POST['property_id'];
        
        /** Bill Data*/
        $billData = $this->BillProperty->find('first', array(
            'conditions' => array('BillProperty.id'=>$bill_property_id),
            'contain'=>array(
                'Bill' => array(
                    'fields'=>array('id','year'),
                    'BillComponent' => array(
                        'fields'=>array('id','comp_name','amount')
                    )
                ),
                'BillPayment'=>array(
                    'fields'=>array('id','amount','date','type','receipt_no','recieved_from')
                )
            ) ,
            'recursive' => 2
        ));
        
        $billData['Bill']['total'] = $this-> __sumBillTotals($billData['Bill']['BillComponent']);
        $billData['Total Payment'] = $this-> __sumPaymentTotals($billData['BillPayment']);
        //debug($billData);
        $this->set(compact('billData'));  
    }
       
    
    function __sumBillTotals($data){
        if(is_array($data)){
            $ttl = 0;
            foreach($data as $value){
               $ttl = $ttl + $value['amount'];
            }
            $returnVal = $ttl; 
        }
        else{
            $totals = $this->BillComponent->find('all', array(
                'fields' => array('SUM(BillComponent.amount) as total'),
                'conditions'=>array('BillComponent.bill_id'=>$data, 'BillComponent.deleted' => 0)
                )
            );
            
            //debug($totals);
            $returnVal = $totals[0][0]['total'];
        }
        return number_format($returnVal,2);
    }
    
    
    function __sumPaymentTotals($data){
        if(is_array($data)){
            $ttl = 0;
            foreach($data as $value){
               $ttl = $ttl + $value['amount'];
            }
            $returnVal = $ttl;
        }
       /// else{
           // $totals = $this->BillComponent->find('all', array(
               // 'fields' => array('SUM(BillComponent.amount) as total'),
               // 'conditions'=>array('BillComponent.bill_id'=>$data, 'BillComponent.deleted' => 0)
               // )
          //  );
            
            //debug($totals);
           // $returnVal = $totals[0][0]['total'];
       // }
        return number_format($returnVal,2);
    }
    
     /**
    * Receipt No. Generator.
    */ 
   function __generateReceiptNo()
	{
		$no_digit = 9; 
		$_token = mt_rand(000000001,999999999);
		$len = strlen($_token);
		$padding = $no_digit - $len;
		$add_zero = '';
		for($x=0;$x<$padding;$x++)
		{
			$add_zero .= '0';
		}
		$better_token = $add_zero.$_token;
		
		return $better_token;
	}
}
?>
